package com.shop.web.converter;

import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 日志打印格式，线程id及name
 *
 * @author Jerry
 * @datetime 2019-11-8 15:53:45
 **/
public class ThreadIdConverter extends ClassicConverter {
    private static AtomicInteger nextId = new AtomicInteger(0);
    private static final ThreadLocal<String> threadId = new ThreadLocal() {
        protected String initialValue() {
            ThreadIdConverter.nextId.incrementAndGet();
            try {
                return "Id(" + String.format("%02d", new Object[]{Integer.valueOf(ThreadIdConverter.nextId.get())}) + "):" + Thread.currentThread().getName();
            } catch (Exception e) {
            }
            return "Id(XX):" + Thread.currentThread().getName();
        }
    };

    public String convert(ILoggingEvent event) {
        return threadId.get();
    }
}
